import { Component, OnInit, Input, OnChanges } from "@angular/core";
import { OneMapService } from "../one-map.service";
import { DatePipe } from "@angular/common";
import { NzMessageService } from "ng-zorro-antd";
import { forkJoin } from "rxjs";
import { DialogBase } from "../dialog-base";
import { UtilService } from 'src/app/core/util/util.service';

@Component({
  selector: "app-dialog-section",
  templateUrl: "./dialog-section.component.html",
  styleUrls: [
    "../dialog-dam/dialog-dam.component.scss",
    "./dialog-section.component.scss"
  ]
})
export class DialogSectionComponent extends DialogBase implements OnChanges {
  @Input() data: any;
  tabs: any[] = ["过程线"];
  // tabs: any[] = ["过程线", "水位流量关系", "旬月特征", "历史同期", "特征信息"];
  activeIdx: number = 0;

  processOpt: any = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        animation: false,
        label: {
          backgroundColor: "#505765"
        }
      }
    },
    legend: {
      data: ["水位"],
      bottom: 10
    },
    xAxis: {
      type: "category",
      axisLabel: {
        // interval: 0
      },
      data: []
    },
    yAxis: [
      {
        name: "水位(m)",
        type: "value"
      }
    ],
    series: [
      {
        name: "水位",
        type: "line",
        smooth: true,
        data: []
      }
    ]
  };

  eigenvalues: any[] = [
    "最高水位",
    "最低水位",
    "平均水位",
    "最高流量",
    "最低流量",
    "平均流量"
  ];
  eigenKeys: any[] = [
    "max_Water_Height",
    "min_Water_Height",
    "avg_Water_Height",
    "max_flux",
    "min_flux",
    "avg_flus"
  ];

  historyTypes: any[] = ["水位", "流量"];
  historyKeys: any[] = ["waterHeight", "flux"];
  // 横轴时间默认为当前点往前推24h
  beginDate = new Date(+new Date() - 24 * 60 * 60 * 1000);
  dmArr: string[] = ['skswz', 'gqdm', 'zygq', 'hd', 'yz', 'hh', 'shg', 'psg', 'zypsg', 'ylz', 'zyylz', 'sqz'];

  constructor(
    private mapService: OneMapService,
    public datePipe: DatePipe,
    private message: NzMessageService,
    private util: UtilService
  ) {
    super(datePipe);
  }

  ngOnChanges() {
    // this.data.code = "HN-7-ZL2";
    console.log(this.data);
    if (this.dmArr.indexOf(this.data.layer) > -1) {
      this.initData();
    }
  }

  initData() {
    // switch (this.data.layer) {
    //   case 'skswz':
    //   case 'gqdm':
    //   case 'zygq':
    //     this.beginDate = new Date(+new Date() - 1 * 24 * 60 * 60 * 1000);
    //     break;
    //   case 'hd':
    //     this.beginDate = new Date(+new Date() - 2 * 24 * 60 * 60 * 1000);
    //     break;
    //   case 'shg':
    //   case 'psg':
    //   case 'zypsg':
    //     this.beginDate = new Date(+new Date() - 3 * 24 * 60 * 60 * 1000);
    //     break;
    // }
    switch (this.activeIdx) {
      case 0:
        this.onQueryProcessList();
        break;
      case 1:
        break;
      case 2:
        this.onQueryMonthList();
        break;
      case 3:
        this.onQueryHistory();
        break;
      case 4:
        break;
    }
  }

  onSelectChange(e) {
    this.activeIdx = e.index;
    this.initData();
  }

  getProcessListSection() {
    const params = {
      stadiaCode: this.data.buildCode || this.data.stadiaCode || this.data.stcd || this.data.properties.Stadia_Code,
      beginTime: this.datePipe.transform(this.beginDate, "yyyy-MM-dd"),
      endTime: this.datePipe.transform(this.endDate, "yyyy-MM-dd")
    };
    switch (this.data.layer) {
      case 'hd':
      case 'yz':
        return this.mapService.queryHDDM(params);
      case 'hh':
        if (this.data.stadiaType == 3) {
          return this.mapService.queryHDDMSK(params);
        } else {
          return this.mapService.queryHDDM(params);
        }
      case 'skswz':
        return this.mapService.querySKSWZ(params);
      case 'gqdm':
      case 'zygq':
        return this.mapService.queryGQDM(params);
      case 'shg':
        return this.mapService.querySHGDM(params);
      case 'psg':
      case 'zypsg':
        return this.mapService.queryPSGDM(params);
      case 'ylz': // 雨量站
      case 'cyylz': // 雨量站
        return this.mapService.queryYLZ(params);
      case 'sqz': // 墒情站
        return this.mapService.querySQZ(params);
    }
  }

  getMonthListSection() {
    return this.mapService.getMonthListSection({
      stadiaCode: this.data.code,
      year: this.curYear,
      history: `${this.year1.getFullYear()},${this.year2.getFullYear()}`
    });
  }

  onQueryProcessList() {
    this.getProcessListSection().subscribe(list => {
      list = list || [];
      const waterHeight = this.data.layer == 'skswz' ? this.getItemValues(list, "rz") : this.data.stadiaType == 3 ? this.getItemValues(list, "heightInside") : this.getItemValues(list, "waterHeight");
      const flow = this.data.stadiaType == 3 ? this.getItemValues(list, 'fluxOut') : this.getItemValues(list, 'flux');
      const whMax = this.util.max(waterHeight);
      const whMin = this.util.min(waterHeight);
      const flowMax = this.util.max(flow);
      const flowMin = this.util.min(flow);
      const flowP = flowMax - flowMin;
      if (this.data.layer == 'ylz' || this.data.layer == 'cyylz') {
        this.processOptChange = {
          legend: {
            data: ["时段降水量", "日降水量"],
            bottom: 10
          },
          xAxis: [
            {
              data: this.getItemValues(list, "tm", true)
            }
          ],
          yAxis: [
            {
              name: "时段降水量(mm)",
              type: "value"
            },
            {
              name: "日降水量(mm)",
              type: "value"
            }
          ],
          series: [
            {
              name: "时段降水量",
              data: this.getItemValues(list, "drp")
            },
            {
              name: "日降水量",
              type: "line",
              yAxisIndex: 1,
              smooth: true,
              data: this.getItemValues(list, "dyp")
            }
          ]
        };
      } else if (this.data.layer == 'sqz') {
        this.processOptChange = {
          legend: {
            data: ["10cm深度含水率", "40cm深度含水率"],
            bottom: 10
          },
          xAxis: [
            {
              data: this.getItemValues(list, "tm", true)
            }
          ],
          yAxis: [
            {
              name: "含水率(%)",
              type: "value"
            }
          ],
          series: [
            {
              name: "10cm深度含水率",
              data: this.getItemValues(list, "slm10")
            },
            {
              name: "40cm深度含水率",
              type: "line",
              smooth: true,
              data: this.getItemValues(list, "slm40")
            }
          ]
        };
      } else {
        this.processOptChange = {
          legend: {
            data: ["水位", "流量"],
            bottom: 10
          },
          xAxis: [
            {
              data: this.data.layer == 'skswz' ? this.getItemValues(list, "tm", true) : this.getItemValues(list, "meaTime", true)
            }
          ],
          yAxis: [
            {
              name: "水位(m)",
              type: "value",
              min: Math.floor(whMin - 1 > 0 ? whMin - 1 : 0),
              max: Math.ceil(whMax + 1)
            },
            {
              name: "流量(m³/s)",
              type: "value",
              min: Math.floor(flowMin - 10 > 0 ? flowMin - 10 : 0),
              max: Math.ceil(flowMax + 10)
            }
          ],
          series: [
            {
              name: "水位",
              data: waterHeight
            },
            {
              name: "流量",
              type: "line",
              yAxisIndex: 1,
              smooth: true,
              data: flow
            }
          ]
        };
        // console.log(this.processOptChange);
      }
    });
  }

  onQueryMonthList() {
    this.getMonthListSection().subscribe((data: any) => {
      // console.log(data);
      this.monthData = data;
      this.changeMonthChart();
    });
  }

  onQueryHistory() {
    const history1 = this.mapService.getProcessListSection({
      ...this.getDateList(this.historyYear1),
      stadiaCode: this.data.code
    });
    const history2 = this.mapService.getProcessListSection({
      ...this.getDateList(this.historyYear2),
      stadiaCode: this.data.code
    });
    forkJoin(history1, history2).subscribe(datas => {
      this.historyLists = datas.map(data => {
        return data["list"];
      });
      this.changeHistoryChart();
    });
  }

  changeMonthChart() {
    console.log(this.selectedIdx);
    const data = this.monthData;
    const keys: any[] = Object.keys(data);
    this.monthOptChange = {
      legend: {
        data: keys.map(k => {
          return k == "historyYear" ? "历史年段" : k;
        })
      },
      series: keys.map(key => {
        return {
          name: key == "historyYear" ? "历史年段" : key,
          type: "bar",
          data: data[key].map(item => {
            return item[this.eigenKeys[this.selectedIdx]];
          })
        };
      })
    };
    // console.log(this.monthOptChange);
  }

  changeHistoryChart() {
    const lists = this.historyLists;
    if (!lists[0].length || !lists[1].length) {
      this.message.error("---无数据---");
      return;
    }
    const xAxisData = lists[0].map(item => {
      return item.meaTime.substr(5);
    });
    const legendData: any[] = [];
    const seriesData: any[] = [];
    lists.map(list => {
      const year = list[0].meaTime.substr(0, 4);
      legendData.push(year);
      seriesData.push({
        name: year,
        type: "line",
        data: list.map(item => {
          return item[this.historyKeys[this.hType]];
        })
      });
    });
    this.historyOptChange = {
      legend: {
        data: legendData
      },
      xAxis: {
        data: xAxisData
      },
      series: seriesData
    };
    // console.log(this.historyOptChange);
  }
}
